/**
 * Created by easy on 15/6/9.
 */
//MoCoop
require.config({
    baseUrl: "../js/MoCoop/",
    paths: {
        jquery: 'components/jquery-2.1.4.min',
        config: 'config',
        fastclick: 'components/fastclick',
        cordova:'cdvfile://localhost/bundle/Shared/cordova'
    }
});
//初始化MoCoop框架
define(['jquery','require','config','fastclick',"cordova"], function($,require,config,FastClick){
    var iOS ="iOS";
    var Android = "Android";
    var Browser = "Browser";
    var mc = {
        "device" : undefined,//设备类型
        "developer" : config.developer,//开发者模式
        "externalURL" : config.externalURL//页面外链地址
    };
    //js错误处理
    function errorHandler(e){
        var error = 'error: '+ e.message+'\n file: '+ e.filename+'\n line: '+ e.lineno;
        if(mc.developer === true){
            alert(error);
        }
        var logInfo = {
            level:"Medium",
            content:error
        };
        mc.appendLog(logInfo);
    }
    window.addEventListener("error",errorHandler,false);
    //初始化MoCoop框架
    mc.init = function (execOnDeviceReady,execOnDocumentReady,options){
        var initOptions = options?options:{};
        if(typeof execOnDeviceReady !== "function"){
            execOnDeviceReady = function(){};
        }
        if(typeof execOnDocumentReady !== "function"){
            execOnDocumentReady = function(){};
        }
        var URL = window.location.toString();
        var isBrowser = (URL.indexOf("http://")  === 0 && mc.developer === false);//浏览器
        var isApp = (URL.indexOf("http://") !== 0 || mc.developer === true);//App
        if (isBrowser){//浏览器
            mc.device = Browser;
        }
        else if(isApp){//App
            var navigatorDevice = navigator.userAgent;
            var isiOS = !!navigatorDevice.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/);//iOS
            var isAndroid = navigatorDevice.indexOf("Android") > -1;//Android
            if (isiOS){//iOS
                mc.device = iOS;
                if(navigatorDevice.indexOf("OS 8") > -1){
                    $("head").append("<style>.divideline{border-bottom: 0.5px solid #bbb!important;}" +
                        ".thinline{border-width: 0.5px!important;}</style>");
                }
            }
            else if(isAndroid){//Android
                mc.device = Android;
            }
            document.addEventListener("deviceready",function(){
                execOnDeviceReady();
            }, false);
        }
        $(function(){
            execOnDocumentReady();
            switch (mc.device){
                case iOS:
                case Android:
                    if(initOptions.withoutFastClick !== true){
                        FastClick.attach(document.body);// 去掉300毫秒延迟
                    }else{
                        document.body.addEventListener('touchstart', function () {});
                    }
                    break;
                case Browser:{
                    document.body.addEventListener('touchstart', function () {});
                    execOnDeviceReady();
                    break;
                }
            }
        });
    };
    //格式化日期
    mc.formatDate = function (timeStamp, timeFormat) {//获取当前时间
        //转换时间格式公共方法
        Date.prototype.Format = function (fmt) {
            var msec =  this.getMilliseconds().toString();
            var milliseconds = function(ms){
                if(ms.length < 3){
                    msec = "0"+ms;
                    milliseconds(msec)
                }
            };
            milliseconds(msec);
            var o = {
                "M+": this.getMonth() + 1,                 //月份
                "d+": this.getDate(),                    //日
                "h+": this.getHours(),                   //小时
                "m+": this.getMinutes(),                 //分
                "s+": this.getSeconds(),                 //秒
                "q+": Math.floor((this.getMonth() + 3) / 3), //季度
                "S": msec,             //毫秒
                "x": this.getHours() < 12 ? "上午" : "下午"
            };


            if (/(y+)/.test(fmt)){
                fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
            }

            for (var k in o){
                if (new RegExp("(" + k + ")").test(fmt)){
                    fmt = fmt.replace(RegExp.$1, (RegExp.$1.length === 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
                }
            }
            return fmt;
        };
        if (timeStamp === undefined || timeStamp === null) {
            if (timeFormat === undefined || timeStamp === null) {
                return new Date().Format('yyyy-MM-dd hh:mm:ss');
            }
            else {
                return new Date().Format(timeFormat);
            }
        } else {
            if (timeFormat === undefined || timeStamp === null) {
                return new Date(timeStamp).Format('yyyy-MM-dd hh:mm:ss');
            }
            else {
                return new Date(timeStamp).Format(timeFormat);
            }
        }
    };
    //获取url参数
    mc.getParamsFromURL = function (URL) {//获取URL中的参数
        URL = URL ? URL : window.location;
        var paramObject = {};
        var paramStr = URL.search.substring(1);
        var params = paramStr.split('&');
        for (var i = 0; i < params.length; i++) {
            var pair = params[i].split('=');
            paramObject[pair[0]] = pair[1];
            paramObject[pair[0]] = decodeURI(paramObject[pair[0]]);
        }
        return paramObject;
    };
    //提示框
    mc.alert = function (message, callback, title, buttonName) {
        var option = {
            title:"",
            message:"",
            buttonName:"确认"
        };
        var alertCallback = function(){};
        if(callback !== undefined){
            alertCallback = callback;
        }
        var execAlert = function(){
            navigator.notification.alert(
                option.message,// message
                alertCallback,// callback
                option.title,// title
                option.buttonName// buttonName
            );
        };
        //iOS 将message显示在title上
        var alertForiOS = function(){
            if(message !== undefined){
                option.title = message;
            }
            if(buttonName !== undefined){
                option.buttonName = buttonName;
            }
            execAlert();
        };
        var alertForAndroid = function(){
            if(message !== undefined){
                option.message = message;
            }
            if(title !== undefined){
                option.title = title;
            }else{
                option.title = "提示";
            }
            if(buttonName !== undefined){
                option.buttonName = buttonName;
            }
            execAlert();
        };
        switch (mc.device) {
            case iOS:
                alertForiOS();
                break;
            case Android:
                alertForAndroid();
                break;
            case Browser:
                alert(message);
                break;
        }
    };
    //确认框
    mc.confirm = function (message, callback, title, buttonLabels) {
        var option = {
            title:"",
            message:"",
            buttonLabels:['取消', '确认']
        };
        var confirmCallback = function (buttonIndex) {
            if(callback !== undefined){
                callback(buttonIndex);
            }
        };
        var execConfirm  = function(){
            navigator.notification.confirm(
                option.message, // message
                confirmCallback,// callback to invoke with index of button pressed
                option.title,           // title
                option.buttonLabels     // buttonLabels
            );
        };
        //iOS 将message显示在title上
        var confirmForiOS = function(){
            if(message !== undefined){
                option.title = message;
            }
            if(buttonLabels !== undefined){
                option.buttonLabels = buttonLabels;
            }
            execConfirm();
        };
        var confirmForAndroid = function(){
            if(message !== undefined){
                option.message = message;
            }
            if(title !== undefined){
                option.title = title;
            }else{
                option.title = "提示";
            }
            if(buttonLabels !== undefined){
                option.buttonLabels = buttonLabels;
            }
            execConfirm();
        };
        switch (mc.device) {
            case iOS:
                confirmForiOS();
                break;
            case Android:
                confirmForAndroid();
                break;
            case Browser:
                if (!window.confirm(title)) {
                    return;
                }
                callback();
                break;
        }
    };
    //页面跳转
    mc.jump = function (pageURL, title, custom, shouldKillForwardPages) {

        switch (mc.device) {
            case iOS:
            case Android:
            {
                var pageJumpsInfo = {
                    pathSuffix: "webroot/" + pageURL,
                    configFileSubPath: "config/theme-page.json",
                    title: title,
                    type: "Direct",
                    showType: "Push",
                    animated: true
                };
                if (shouldKillForwardPages !== undefined) {
                    if (shouldKillForwardPages === "all") {
                        pageJumpsInfo.shouldKillForwardPages = true;
                    } else if (typeof shouldKillForwardPages === "number") {
                        pageJumpsInfo.killForwardPageCount = shouldKillForwardPages;
                    }
                }
                if(custom !== undefined){
                    pageJumpsInfo.configFileSubPath = "config/theme-"+custom+".json";
                }
                if (mc.developer === true) {
                    pageJumpsInfo.basedURL = mc.externalURL;
                }
                jumpToPage(pageJumpsInfo);
                break;
            }
            case Browser:
                window.location.href = pageURL;
                break;
        }
    };
    //返回指定页面
    mc.backToTargetPage = function(targetURL){
        switch (mc.device) {
            case iOS:
            case Android:
                targetURL = "webroot/"+targetURL;
                backToSpecifyPage(targetURL, true);
                break;
            case Browser:
                break;
        }
    };
    //返回上一页
    mc.backToPrePage = function () {
        switch (mc.device) {
            case iOS:
                backToForwardPage(true);
                break;
            case Android:
                backToForwardPage();
                break;
            case Browser:
                window.history.go(-1);
                break;
        }
    };
    //显示页面内容
    mc.showContent = function () {
        switch (mc.device) {
            case iOS:
            case Android:
                showMeRightNow();
                break;
        }
    };
    //ajax请求
    mc.beginAsyncAjax = function(URL, requestData, type, callback, options){

        switch (mc.device) {
            case iOS:
            case Android:
                beginAsyncAjax(URL, requestData, type, callback, options);
                break;
            case Browser:
                break;
        }
    };
    //获取登录人信息
    mc.getUserInfo = function (callback) {
        switch (mc.device) {
            case iOS:
            case Android:
                getUserInfo(function(data){
                    if(data.result === true){
                        mc.userInfo = data.userInfo;
                    }
                    callback();
                });
                break;
        }
    };
    //临时存储
    mc.manageTempData = function(action,callback,key,value){
        switch (mc.device) {
            case iOS:
            case Android:
                switch(action){
                    case "get":
                        getTempData(key,callback);
                        break;
                    case "set":
                        setTempData(key,value,callback);
                        break;
                    case "remove":
                        removeTempData(key,callback);
                        break;
                    case "clear":
                        clearTempDatas(callback);
                        break;
                }
                break;
            case Browser:
                break;
        }
    };
    // 普通 "Normal";
    // 进度 "Progress";
    // 成功 "Succeed";
    // 失败  "Failed";
    // Info  "Info";
    //提示
    mc.notification = function(message,type,progress){
        switch (mc.device) {
            case iOS:
            case Android:
                if(type !== "Close"){
                    var info = {
                        text:message,
                        progress:progress,
                        type:type
                    };
                    showHUD(info,null);
                }else{
                    dismissHUD(null);
                }
                break;
            case Browser:
                break;
        }
    };
    //获取已下载文件的本地路径
    mc.getDownloadedFileURL = function(URL,filename, callback){
        switch (mc.device) {
            case iOS:
                getDownloadedFileURL(URL, callback);
                break;
            case Android:
                getDownloadedFileURL(filename, callback);
                break;
            case Browser:
                break;
        }
    };
    //下载文件
    mc.downloadFile = function(URL, destinationFileName, options, callback){
        switch (mc.device) {
            case iOS:
            case Android:
                downloadFile(URL, destinationFileName, options, callback);
                break;
            case Browser:
                break;
        }
    };
    //取消下载
    mc.cancelDownload = function(ID, callback){
        switch (mc.device){
            case iOS:
            case Android:
                cancelDownload(ID, callback);
                break;
            case Browser:
                break;
        }
    };
    //打开附件
    mc.openFile = function(fileURL, isInOthersArr, callback){
        switch (mc.device) {
            case iOS:
                if(isInOthersArr === true){
                    openFileVia3rd(fileURL, callback);
                }else{
                    openFile(fileURL, callback);
                }
                break;
            case Android:
                openFile(fileURL, callback);
                break;
            case Browser:
                break;
        }
    };
    //获取服务地址
    mc.getServiceURL = function(callback){
        switch (mc.device) {
            case iOS:
                getMainURLForRequest(function(data){
                    if(data.result === true){
                        callback(data.mainURL);
                    }else{
                        mc.alert(data.error);
                    }

                });
                break;
            case Android:
                getServerIP(function(data){
                    if(data.result === true){
                        callback(data.serverIP);
                    }else{
                        mc.alert(data.error);
                    }
                });
                break;
            case Browser:
                break;
        }

    };
    /*
     * info包含的字段
     * level: 类型LogLevel
     * content: 类型String
     * createTimeStamp: 时间戳
     * ESBSerialNumber 可选
     * ApiName 可选
     * ApiURL 可选
     * ApiResponseBody 可选
     * */
    //添加错误日志
    mc.appendLog = function(info,callback){
        info.createTimeStamp = new Date().getTime();
        switch (mc.device) {
            case iOS:
                appendLog(info,callback);
                break;
            case Android:
                saveErrorLogs(info,callback);
                break;
            case Browser:
                break;
        }
    };
    //修改nav按钮
    mc.updatePageBarButtonItem = function(direction, index, info, callback){
        switch (mc.device) {
            case iOS:
            case Android:
                updatePageBarButtonItem(direction, index, info, callback);
                break;
            case Browser:
                break;
        }
    };
    return mc;

});